package com.test.intercept;

import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Field;
import java.sql.SQLException;

@Slf4j
public class SqlIntercept implements InnerInterceptor {
    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {

        String sql = boundSql.getSql();
        log.info("boundSql.getSql():{}",sql);

        sql = sql + " where tenant_id_ = 2";

        ReflectUtil.setFieldValue(boundSql, "sql", sql);

//        try {
//            Field sqlFiled = BoundSql.class.getDeclaredField("sql");
//            sqlFiled.setAccessible(true);
//            sqlFiled.set(boundSql, sql);
//        } catch (NoSuchFieldException e) {
//            throw new RuntimeException(e);
//        }catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }

//        InnerInterceptor.super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
    }
}
